package com.zhuhjay.boot.controller;

import com.zhuhjay.constant.MessageConstant;
import com.zhuhjay.constant.RedisMessageConstant;
import com.zhuhjay.domain.http.Result;
import com.zhuhjay.utils.ValidateCodeUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author ZhuHJay
 * @date 2022/4/3 22:30
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    private final StringRedisTemplate redisTemplate;
    public ValidateCodeController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/order/{telephone}")
    public Result sendOrderCode(@PathVariable("telephone")String telephone){
        try{
            // 生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            // 发送短信(假装)
            // 将短信数据存储到redis, 设置过期时间为5分钟, 键为 order:telephone
            redisTemplate.opsForValue()
                    .set(RedisMessageConstant.SENDTYPE_ORDER + ":" + telephone, String.valueOf(code),
                            5, TimeUnit.MINUTES);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }catch (Exception e){
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @GetMapping("/login/{telephone}")
    public Result sendLoginCode(@PathVariable("telephone")String telephone){
        try{
            // 生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            // 发送短信(假装)
            // 将短信数据存储到redis, 设置过期时间为5分钟, 键为 order:telephone
            redisTemplate.opsForValue()
                    .set(RedisMessageConstant.SENDTYPE_LOGIN + ":" + telephone, String.valueOf(code),
                            5, TimeUnit.MINUTES);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }catch (Exception e){
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

}
